﻿using CsvHelper;
using LeakView.common;
using LeakView.database;
using LeakView.view.controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LeakView.view
{
    public partial class FormNetworkAlarmHistory : Form
    {
        public FormNetworkAlarmHistory()
        {
            InitializeComponent();
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            using (new LoadingStarter())
            using (var db = new SqliteDbContext())
            {
                var values = db.NetworkAlarmMaster.Where(t => t.Time >= this.dateTimePickerStart.Value && t.Time <= this.dateTimePickerEnd.Value).ToList();
                this.setValues(values);
            }
        }

        private void setValues(List<NetworkAlarmEntry> entries)
        {
            this.dataGridView1.Rows.Clear();

            entries.ForEach(entry =>
            {
                int index = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index].Cells[0].Value = entry.ID;
                this.dataGridView1.Rows[index].Cells[1].Value = entry.Time.ToString();
                this.dataGridView1.Rows[index].Cells[2].Value = entry.NodeId;
                this.dataGridView1.Rows[index].Cells[3].Value = entry.NodeName;
                this.dataGridView1.Rows[index].Cells[4].Value = entry.State ? "在线" : "离线";
                this.dataGridView1.Rows[index].Tag = entry;
            });
        }

        private void buttonExport_Click(object sender, EventArgs e)
        {
            ExportCSV.export(this.dataGridView1);
            /*
            if (this.dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("没有可以导出的数据！");
                return;
            }

            var result = this.saveFileDialog.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }

            using (var writer = new StreamWriter(this.saveFileDialog.FileName, false, Encoding.GetEncoding(936)))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                foreach (DataGridViewColumn column in this.dataGridView1.Columns)
                {
                    csv.WriteField(column.HeaderText);
                }
                csv.NextRecord();

                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    for (var i = 0; i < this.dataGridView1.Columns.Count; i++)
                    {
                        csv.WriteField(row.Cells[i].Value.ToString());
                    }
                    csv.NextRecord();
                }
            }
            */
        }
    }
}
